//
//  PublishWantJobMessageTC.swift
//  甜言蜜语
//
//  Created by yingli_yanfa_liuxingyu on 16/8/4.
//  Copyright © 2016年 wl. All rights reserved.
//

import UIKit
import ActionSheetPicker_3_0
import SVProgressHUD
class PublishWantJobMessageTC: UITableViewController,UIImagePickerControllerDelegate, UINavigationControllerDelegate,UIActionSheetDelegate, ActionSheetCustomPickerDelegate, UITextViewDelegate{
    var actionSheet: UIActionSheet? = nil
    var imagePicker: UIImagePickerController? = nil

    @IBOutlet weak var imgscr: UIImageView!
    @IBOutlet weak var name: UITextField!
    @IBOutlet weak var birthday: UILabel!
    @IBOutlet weak var birthdayPlace: UILabel!
    @IBOutlet weak var workArea: UILabel!
    @IBOutlet weak var workAreaPlace: UILabel!
    @IBOutlet weak var education: UILabel!
    @IBOutlet weak var educationPlace: UILabel!
    @IBOutlet weak var pay: UILabel!
    @IBOutlet weak var payPlace: UILabel!
    @IBOutlet weak var life: UILabel!
    @IBOutlet weak var lifePlace: UILabel!
    @IBOutlet weak var position: UILabel!
    @IBOutlet weak var positionPlace: UILabel!
    @IBOutlet weak var tel: UITextField!
    @IBOutlet weak var requir: UITextView!
    @IBOutlet weak var manBtn: UIButton!
    @IBOutlet weak var femaleBtn: UIButton!
    @IBOutlet weak var tipsLbl: UILabel!
    @IBOutlet weak var tipsIv: UIImageView!
    
    @IBOutlet weak var requirePlace: UILabel!
    var sex: String!
    var IMG: UIImage?
    var nilArr: [UIImage] = []//形象展示的数组
    var msg: regiestInfo?
    var fooetView = PublishWantJobMessageFooter.create()
    
    var index1: NSInteger = 0 // 省下标
    var index2: NSInteger = 0 // 市下标
    var index3: NSInteger = 0 // 区下标
    
    var provinceArr: NSArray! //省
    var countryArr: NSArray! // 市
    var districtArr: NSArray! // 区
    var addressArr: NSArray! // 解析出来的最外层的数组
    
    override func viewDidLoad() {
        super.viewDidLoad()
         publicMethod.setHUDStyle()
        self.requir.delegate = self
        self.requir.layer.masksToBounds = true
        self.requir.layer.borderWidth = 1
        self.requir.layer.borderColor = UIColor.lightGrayColor().CGColor
        self.imgscr.hidden = true
         fooetView.nextStepBtn .addTarget(self, action: #selector(PublishWantJobMessageTC.nextStepBtn), forControlEvents: UIControlEvents.TouchUpInside )
        //self.imgscr.hidden = true
        if (actionSheet == nil) {
            self.actionSheet = UIActionSheet(title: "选择照片",delegate: self, cancelButtonTitle: "取消", destructiveButtonTitle: nil, otherButtonTitles: "拍照", "从手机相册选择")
        }

        self.tableView.tableFooterView = fooetView
        self.manBtn.setImage(UIImage(named: "unchecked"), forState: UIControlState.Normal)
        self.femaleBtn.setImage(UIImage(named: "unchecked"), forState: UIControlState.Normal)
        
        self.calculateFirstData()
    }
    //MARK:target
    @IBAction func sexBtnClicked(sender: UIButton){
        if sender == self.manBtn{
            self.sex = "男"
            self.manBtn.setImage(UIImage(named: "checked"), forState: UIControlState.Normal)
            self.femaleBtn.setImage(UIImage(named: "unchecked"), forState: UIControlState.Normal)
            
        }
        if sender == self.femaleBtn{
            self.sex = "女"
             self.femaleBtn.setImage(UIImage(named: "checked"), forState: UIControlState.Normal)
            self.manBtn.setImage(UIImage(named: "unchecked"), forState: UIControlState.Normal)
        }
    }
    override func viewWillDisappear(animated: Bool) {
        SVProgressHUD.dismiss()
        super.viewWillDisappear(animated)
    }
    
    //MARK:UITextViewDelegate
    func textViewDidChange(textView: UITextView) {
        let str = textView.text
        if str.characters.count > 0{
            self.requirePlace.alpha = 0
        }else{
            self.requirePlace.alpha = 1
        }
    }
    
    override func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
        if(cell.respondsToSelector(Selector("setSeparatorInset:"))) {
            cell.separatorInset = UIEdgeInsetsMake(0, 0, 0, 0)
        }
        if(cell.respondsToSelector(Selector("setLayoutMargins:"))) {
            cell.layoutMargins = UIEdgeInsetsMake(0, 0, 0, 0)
        }
    }
    func calculateFirstData(){
        
        loadFirstData()
        let cityNameArr = NSMutableArray()
        
        print(addressArr.count)
        for cityName in (addressArr[index1].allValues.first) as! NSArray {
            
            let name1 = (cityName as! NSDictionary).allKeys.first
            cityNameArr.addObject(name1!)
        }
        // 组装对应省下面的市
        countryArr = cityNameArr
        
        districtArr = addressArr[index1].allObjects[0][index2].allValues[0] as! NSArray
        
    }
    func loadFirstData(){
        
        let path = NSBundle.mainBundle().pathForResource("address", ofType: "json")
        print(path)
        
        let data = NSData.init(contentsOfFile: path!)
        
        guard let myArr = try? NSJSONSerialization.JSONObjectWithData(data!, options: .AllowFragments) else {
            
            return
        }
        
        addressArr = myArr as! NSArray
        
        let firstName = NSMutableArray()
        for dict in addressArr {
            
            let name = (dict as! NSDictionary).allKeys.first
            firstName.addObject(name!)
        }
        provinceArr = firstName
        
        
    }
    //MARK: UIPickerViewDataSource Implementation
    
    func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int {
        return 2
    }
    func pickerView(_pickerView: UIPickerView,
                    numberOfRowsInComponent component: Int) -> Int{
        switch (component)
        {
        case 0: return self.provinceArr.count;
        case 1: return self.countryArr.count;
        default:break;
        }
        return 0;
    }
    
    func pickerView(pickerView: UIPickerView,
                    titleForRow row: Int,
                                forComponent component: Int) -> String?{
        
        switch (component)
        {
        case 0: return self.provinceArr[row] as? String
        case 1: return self.countryArr[row] as? String
        default:break;
        }
        return nil;
    }
    func pickerView(pickerView: UIPickerView,
                    viewForRow row: Int,
                               forComponent component: Int,
                                            reusing view: UIView?) -> UIView{
        
        
        let label: UILabel! = UILabel()
        label!.font = UIFont.systemFontOfSize(14)
        
        var title = ""
        switch component {
        case 0:
            title = self.provinceArr[row] as! String
        case 1:
            title = self.countryArr[row] as! String
        default:
            break
        }
        
        label!.textAlignment = NSTextAlignment.Center
        label!.text = title
        return label!
        
    }
    func pickerView(pickerView: UIPickerView,
                    didSelectRow row: Int,
                                 inComponent component: Int){
        switch component {
        case 0:
            self.index1 = row
            self.index2 = 0
           
            // 滚动的时候都要进行一次数组的刷新
            self.calculateFirstData()
            pickerView.reloadComponent(1)
            pickerView.selectRow(0, inComponent: 1, animated: true)
           
            
        case 1:
            self.index2 = row
        default:
            break
        }
        
    }
    //MARK:点击完成的按钮时执行
    func actionSheetPickerDidSucceed(actionSheetPicker: AbstractActionSheetPicker!, origin: AnyObject!) {
        var detailAddress = String()
        if self.index1 < self.provinceArr.count {
            let firstAddress = self.provinceArr[self.index1]
            detailAddress += firstAddress as! String
        }
        if self.index2 < self.countryArr.count {
            let secondAddress = self.countryArr[self.index2]
            detailAddress += secondAddress as! String
        }
      
        // 此界面显示
        print(detailAddress)
        self.workAreaPlace.alpha = 0
        self.workArea.text = detailAddress
    }
    // MARK: - Table view delegate
    override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
        
        tableView.deselectRowAtIndexPath(indexPath, animated: true)
        if indexPath.row == 0{
            self.actionSheet!.showInView(self.view!)
        }
        if indexPath.row == 2{
            
            self.tel.resignFirstResponder()
            self.requir.resignFirstResponder()
            self.name.resignFirstResponder()
            
            ActionSheetDatePicker.showPickerWithTitle("出生年月", datePickerMode: UIDatePickerMode.Date, selectedDate: NSDate(), doneBlock: {(picker: ActionSheetDatePicker!, selectedDate: AnyObject!, origin: AnyObject!) -> Void in
                
                    let obj = selectedDate as! NSDate
                
                    self.birthdayPlace.alpha = 0
                
                    self.birthday.text = publicMethod.dataFromString(obj)
                
                    }, cancelBlock: {(picker: ActionSheetDatePicker!) -> Void in
                        print("cancel")
                }, origin: self.view)

        }
        if indexPath.row == 3{
            
           
            self.tel.resignFirstResponder()
            self.requir.resignFirstResponder()
            self.name.resignFirstResponder()
            
            ActionSheetCustomPicker.showPickerWithTitle("请选择位置区域", delegate: self, showCancelButton: true, origin: self.view, initialSelections: [index1, index2])
           
            
        }
        if indexPath.row == 4{
            self.tel.resignFirstResponder()
            self.requir.resignFirstResponder()
            self.name.resignFirstResponder()
            
            ActionSheetMultipleStringPicker.showPickerWithTitle("最高学历", rows:[["高中以下", "高中", "中专/技校","大专","本科","硕士","博士","MBA/EMBA"]],initialSelection: [1,1], doneBlock: {
                picker, values, indexes in
                let obj = (indexes as! NSArray)[0] as! String
                self.educationPlace.alpha = 0
                self.education.text = obj
                return
                }, cancelBlock: { ActionMultipleStringCancelBlock in return }, origin: self.view)
            
        }
        if indexPath.row == 5{
           
            self.tel.resignFirstResponder()
            self.requir.resignFirstResponder()
            self.name.resignFirstResponder()
            
            ActionSheetMultipleStringPicker.showPickerWithTitle("期望薪资", rows:[["面议", "1000-2000元", "2000-3000元","3000-5000元","5000-8000元","80000-10000元","120000-20000元","20000-25000元","25000以上"]],initialSelection: [1,1], doneBlock: {
                picker, values, indexes in
                let obj = (indexes as! NSArray)[0] as! String
                self.payPlace.alpha = 0
                self.pay.text = obj
                
                
                return
                }, cancelBlock: { ActionMultipleStringCancelBlock in return }, origin: self.view)
            
        }
        if indexPath.row == 6{
           
            self.tel.resignFirstResponder()
            self.requir.resignFirstResponder()
            self.name.resignFirstResponder()
            
            ActionSheetMultipleStringPicker.showPickerWithTitle("工作经验", rows:[["不限", "一年以下", "1-2年","3-5年" ,"6-7年","8-10年","10年以上"]],initialSelection: [1,1], doneBlock: {
                picker, values, indexes in
                let obj = (indexes as! NSArray)[0] as! String
                self.lifePlace.alpha = 0
                self.life.text = obj
        
                return
                }, cancelBlock: { ActionMultipleStringCancelBlock in return }, origin: self.view)
            
        }
        if indexPath.row == 7{
            
            self.tel.resignFirstResponder()
            self.requir.resignFirstResponder()
            self.name.resignFirstResponder()
            
            ActionSheetMultipleStringPicker.showPickerWithTitle("期望职位", rows:[["店长", "美容师", "业务经理","讲师","业务"]],initialSelection: [1,1], doneBlock: {
                picker, values, indexes in
                
                let obj = (indexes as! NSArray)[0] as! String
                self.positionPlace.alpha = 0
                self.position.text = obj
                
                return
                }, cancelBlock: { ActionMultipleStringCancelBlock in return }, origin: self.view)
            
        }
        
    }
    //MARK:UITextFieldDelegate
    func textFieldDidEndEditing(textField: UITextField){
        if textField == self.name{
            self.name.text = textField.text
        }
        if textField == self.tel{
            self.tel.text = textField.text
        }
        if textField == self.requir{
            self.requir.text = textField.text
        }
        
    }

    func nextStepBtn(sender: UIButton) -> Void {
        sender.selected = !sender.selected
        if sender.selected{
            if self.name.text == ""{
                SVProgressHUD.showErrorWithStatus("请填写名字")
                
                return
            }
            if self.birthday.text == ""{
                SVProgressHUD.showErrorWithStatus("请填写生日")
                
                return
            }
            if self.workArea.text == ""{
                SVProgressHUD.showErrorWithStatus("请填写工作区域")
                
                return
            }
            if self.education.text == ""{
                SVProgressHUD.showErrorWithStatus("请填写最高学历")
                
                return
            }
            if self.life.text == ""{
                SVProgressHUD.showErrorWithStatus("请填写工作经验")
                
                return
            }
            if self.position.text == ""{
                SVProgressHUD.showErrorWithStatus("请填写期望职位")
                
                return
            }
            if self.tel.text == ""{
                SVProgressHUD.showErrorWithStatus("请填写联系电话")
                
                return
            }
            if self.requir.text == ""{
                SVProgressHUD.showErrorWithStatus("请填写自我评价")
                
                return
            }else{
                
                let param = ["name": self.name.text!, "sex": self.sex!, "birthday": self.birthday.text!, "unitarea": self.workArea.text!, "education": self.education.text!, "pay": self.pay.text!, "lift": self.life.text!, "positiontype": self.position.text!,  "tel": self.tel.text!, "requirement": self.requir.text!,"type": "求职"]
                 SVProgressHUD.showWithStatus("加载中...")
                DataTool.uploadLicense(nilArr, uploadStyleImage: nilArr, imgsrc: self.IMG, type: "发布求职", param: param, completionHandler: {(newModel) in
                    guard let newDataes = newModel else {
                        return
                    }
                    SVProgressHUD.dismiss()
                    print(newDataes)
                    self.msg = newModel
                    let vc = self.storyboard?.instantiateViewControllerWithIdentifier("ImproveResumeTC") as! ImproveResumeTC
                    vc.id = self.msg?.id
                    self.navigationController?.pushViewController(vc, animated: true)
                })
            }

        }else{
            // 第二次点击
        }
        
    }
    
    //MARK:actionSheetDelegate
    func actionSheet(actionSheet: UIActionSheet, clickedButtonAtIndex buttonIndex: Int) {
        if buttonIndex == 1 {
            //拍照
            var sourceType = UIImagePickerControllerSourceType.Camera
            if !UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.Camera){
                
                sourceType = UIImagePickerControllerSourceType.PhotoLibrary
            }
            let picker = UIImagePickerController()
            picker.delegate = self
            picker.allowsEditing = true//设置可编辑
            picker.sourceType = sourceType
            self.presentViewController(picker, animated: true, completion: nil)//进入照相界面
            
        }else if buttonIndex == 2{
            //相册
            let pickerImage = UIImagePickerController()
            if !UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.PhotoLibrary){
                pickerImage.sourceType = UIImagePickerControllerSourceType.PhotoLibrary
                pickerImage.mediaTypes = UIImagePickerController.availableMediaTypesForSourceType(pickerImage.sourceType)!
            }
            
            pickerImage.delegate = self
            
            pickerImage.allowsEditing = true
            
            self.presentViewController(pickerImage, animated: true, completion: nil)
        }
        
    }
    //MARK:UIImagePickerControllerDelegate
    func imagePickerController(picker: UIImagePickerController,didFinishPickingMediaWithInfo info: [String : AnyObject]){
        
        var img: UIImage!
        //self.imgscr.hidden = false
        img = info[UIImagePickerControllerEditedImage] as! UIImage
        self.imgscr.image = img
        self.IMG = img
        self.tipsLbl.hidden = true
        self.imgscr.hidden = false
        self.tipsIv.hidden = true
        picker.dismissViewControllerAnimated(true, completion: nil)
        
    }
    func imagePickerControllerDidCancel(picker: UIImagePickerController){
        
        print("cancel--------->>")
        
        picker.dismissViewControllerAnimated(true, completion: nil)
        
    }

    
   

}
